package com.googlecode.grs.robot;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import com.googlecode.grs.ui.Drawable;
import com.googlecode.grs.ui.SimulatorUI;

/**
 * RobotUI draws an entire robot, including sensors, and frame It simply calls
 * the draw() method from each component, and gets data from the environment to
 * get position for frame
 * 
 * It should only be used by SimulatorUI, which draws it.
 * 
 * @see SimulatorUI
 * 
 * @author ajc
 * 
 */
public class DrawnRobot extends Thread implements Drawable {

	private Moveable robot;
	private ArrayList<DrawnRobotComponent> components;

	/**
	 * 
	 * @param env
	 *            The environment that the DrawnRobot exists in
	 */
	public DrawnRobot(Moveable robot) {
		this.robot = robot;
		components = new ArrayList<DrawnRobotComponent>();
	}

	/**
	 * Adds this component to be drawn when the Robot is drawn.
	 * 
	 * @param component
	 *            a draweable robot component to draw
	 */
	public void addRobotComponent(DrawnRobotComponent component) {
		components.add(component);
	}

	/**
	 * Removes this component, to stop drawing when the robot is drawn
	 */
	public void removeRobotComponent(DrawnRobotComponent component) {
		components.remove(component);
	}

	public Moveable getRobot() {
		return robot;
	}

	@Override
	/**
	 * Called on a regular clock by SimulatorUI. Thus there is a regular pattern of drawing
	 * @see SimulatorUI
	 */
	public void draw(Graphics g) {
		drawRobot(g);
		drawComponents(g);

	}

	private void drawComponents(Graphics g) {
		for (DrawnRobotComponent comp : components) {
			comp.draw(g);
		}

	}

	private void drawRobot(Graphics g) {
		g.setColor(Color.BLACK);

		// draw robot
		g.drawOval((int) robot.getX() - 5, (int) robot.getY() - 5, 10, 10);// TODO
																			// magic
																			// numbers

		g.setColor(Color.RED);
		// robot orientation drawn as a red line
		g.drawLine((int) robot.getX(), (int) robot.getY(),
				(int) (robot.getX() + 9 * Math.cos(robot.getHeading())),
				(int) (robot.getY() + 9 * Math.sin(robot.getHeading())));
		g.setColor(Color.BLACK);
	}
}
